package com.slfx.idgen.demo.idgen.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpAddressUtil {

    private IpAddressUtil() {
    }

    public static String getIp() {
        String sip = "";
        InetAddress ip = null;
        try {
            boolean bfindip = false;
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                if (bfindip) {
                    break;
                }
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = ips.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
                        bfindip = true;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("can not get IP address...");
        }
        if (null != ip) {
            sip = ip.getHostAddress();
        }
        return sip;
    }
}
